<template>
	<div class="order-detail-page">
		<!-- 顶部渐变背景 -->
		<div class="top-gradient"></div>

		<!-- 模糊椭圆 -->
		<div class="ellipse-1"></div>
		<div class="ellipse-2"></div>

		<!-- 导航栏 -->
		<van-nav-bar
			:title="t('orderDetail.title')"
			left-arrow
			@click-left="goBack"
			fixed
			placeholder
			class="custom-nav-bar"
		/>

		<!-- 成功图标和文字 -->
		<div class="success-section">
			<div class="success-icon">
				<img
					src="@/assets/success.svg"
					:alt="t('successPopup.title')"
					width="48"
					height="48"
				/>
			</div>
			<div class="success-text">{{ t('successPopup.title') }}</div>
		</div>

		<!-- 详情卡片 -->
		<div class="detail-card">
			<!-- 基本信息区域 -->
			<div class="info-section">
				<div class="info-row">
					<div class="info-icon">
						<div class="icon profile-icon"></div>
					</div>
					<div class="info-content">{{ orderDetail.name }}</div>
				</div>

				<div class="info-row">
					<div class="info-icon">
						<div class="icon map-pin-icon"></div>
					</div>
					<div class="info-content">{{ orderDetail.address }}</div>
				</div>

				<div class="info-row">
					<div class="info-icon">
						<div class="icon calendar-icon"></div>
					</div>
					<div class="info-content">
						{{ orderDetail.appointmentTime }}
					</div>
				</div>

				<div class="info-row">
					<div class="info-icon">
						<div class="icon phone-icon"></div>
					</div>
					<div class="info-content">
						{{ orderDetail.phone }}
						{{
							orderDetail.secondaryPhone
								? orderDetail.secondaryPhone
								: ''
						}}
					</div>
				</div>
			</div>

			<!-- 分割线 -->
			<div class="divider"></div>

			<!-- 详细选项区 -->
			<div class="options-section">
				<div class="option-row">
					<div class="option-label">{{ orderDetail.doorInfo }}</div>
					<div class="option-value" v-if="orderDetail.doorPassword">
						{{ orderDetail.doorPassword }}
					</div>
				</div>

				<div class="option-row">
					<div class="option-label">{{ orderDetail.placement }}</div>
					<div
						class="option-value"
						v-if="orderDetail.placementPhotoUrl"
						@click="viewPhoto"
					>
						{{ t('delivery.viewPhoto') }}
					</div>
					<!-- 如果没有图片，不显示"查看照片"按钮 -->
				</div>
				<!-- 暂时不展示上门和安装服务 -->
				<!-- <div class="option-row">
          <div class="option-label">{{ orderDetail.needUpstairs ? '需要送货上楼' : '不需要送货上楼' }}</div>
          <div class="option-value" @click="viewPhoto">{{ $t('delivery.viewPhoto') }}</div>
        </div>

        <div class="option-row">
          <div class="option-label">{{ orderDetail.needInstallation ? '需要安装' : '不需要安装' }}</div>
        </div> -->
			</div>

			<!-- 修改预约按钮 -->
			<div class="edit-btn" @click="editAppointment">
				{{ t('orderDetail.editAppointment') }}
			</div>
		</div>

		<!-- 底部客服 -->
		<!-- <div class="customer-service" @click="callCustomerService">
      <van-icon name="service-o" color="#B7B7B7" size="20" />
      <span>{{ $t('orderDetail.customerService') }}</span>
    </div> -->

		<!-- 底部安全区 -->
		<div class="bottom-safe-area"></div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast, closeToast, showImagePreview } from 'vant'
import 'vant/es/toast/style'
import 'vant/es/nav-bar/style'
import 'vant/es/image-preview/style'
import { api } from '../utils/request'
import { useI18n } from 'vue-i18n'
import { setLocale } from '../i18n'

const router = useRouter()
const route = useRoute()
const { t } = useI18n()

// 订单详情数据
const orderDetail = ref({
	name: '',
	address: '',
	appointmentTime: '',
	phone: '',
	secondaryPhone: '',
	doorInfo: '',
	doorPassword: '',
	placement: '',
	placementPhotoUrl: '',
	needUpstairs: false,
	needInstallation: false,
})

// 获取路由参数中的tracking_number
const trackingNumber = ref('')

// 组件挂载时获取预约详情
onMounted(async () => {
	// 打印更多调试信息
	console.log('OrderDetail 组件挂载')
	console.log('路由参数:', route.query)
	console.log('完整URL:', window.location.href)

	// 检查URL中是否有语言参数
	if (route.query.lang && typeof route.query.lang === 'string') {
		console.log('检测到URL中的语言参数:', route.query.lang)
		setLocale(route.query.lang)
	}

	// 从URL参数获取tracking_number
	if (route.query.tracking_number) {
		trackingNumber.value = route.query.tracking_number as string
		console.log('获取到运单号(从URL):', trackingNumber.value)

		// 获取预约详情
		await fetchAppointmentDetail()
	} else {
		console.error('未获取到有效的运单号')
		console.error('当前路由参数:', JSON.stringify(route.query))

		// 尝试使用localStorage中存储的运单号
		const savedTrackingNumber = localStorage.getItem(
			'current_tracking_number'
		)
		console.log('localStorage中的运单号:', savedTrackingNumber)

		if (savedTrackingNumber) {
			trackingNumber.value = savedTrackingNumber
			console.log('使用localStorage中的运单号:', trackingNumber.value)
			await fetchAppointmentDetail()
		} else {
			// 如果仍然没有找到，显示错误提示
			console.error('未找到有效的跟踪号，无法加载预约详情')
			showToast({
				message: t('errors.noTrackingNumber'),
				position: 'middle',
				type: 'fail',
				duration: 3000,
			})

			// 3秒后自动返回首页
			setTimeout(() => {
				router.push('/')
			}, 3000)
		}
	}
})

// 获取预约详情
async function fetchAppointmentDetail() {
	try {
		console.log('开始请求预约详情, tracking_number:', trackingNumber.value)
		showLoadingToast({
			message: t('orderDetail.loading'),
			forbidClick: true,
		})

		const response = await api.getAppointmentInfo(trackingNumber.value)
		console.log('API响应:', response)

		closeToast()

		if (response.code === 0 && response.data) {
			console.log('获取到的预约详情数据:', response.data)

			// 解析API返回的数据，填充到页面
			const { info, config } = response.data

			// 基本信息
			orderDetail.value.name = info.customer_name || ''
			orderDetail.value.address = info.address || ''
			orderDetail.value.phone = info.mobile || ''
			orderDetail.value.secondaryPhone = info.other_mobile || ''

			// 大门信息 - 使用多语言
			orderDetail.value.doorInfo =
				info.is_gate === 1
					? t('doorInfo.passwordTitle')
					: t('doorInfo.noDoor')
			orderDetail.value.doorPassword = info.gate_code || ''

			// 摆放方式
			if (
				info.storage_place >= 0 &&
				config.storage_list &&
				config.storage_list.length > 0
			) {
				const placeIndex =
					info.storage_place == 0 ? 0 : info.storage_place - 1
				console.log('摆放方式索引:', placeIndex)
				console.log('摆放方式列表:', config.storage_list)
				orderDetail.value.placement = config.storage_list[placeIndex]
				if (
					placeIndex >= 0 &&
					placeIndex < config.storage_list.length
				) {
					orderDetail.value.placement =
						config.storage_list[placeIndex]
					console.log('摆放方式:', orderDetail.value.placement)
				}
			}

			// 摆放位置图片URL
			orderDetail.value.placementPhotoUrl = info.storage_place_url || ''
			console.log('摆放位置图片URL:', orderDetail.value.placementPhotoUrl)

			// 上楼和安装信息
			orderDetail.value.needUpstairs = info.is_upstairs === 1
			orderDetail.value.needInstallation = info.is_installation === 1

			// 预约时间
			if (info.is_appointment === 1 && info.appointment_year) {
				const formattedDate = `${info.appointment_year}.${info.appointment_month}.${info.appointment_day}`
				orderDetail.value.appointmentTime = `${formattedDate} ${
					info.appointment_time || ''
				}`
			}
		} else {
			console.error('API返回错误:', response)
			showToast({
				message: response.msg || t('errors.apiError'),
				position: 'middle',
				type: 'fail',
			})
		}
	} catch (error) {
		closeToast()
		console.error('获取预约详情出错:', error)
		showToast({
			message: t('errors.networkError'),
			position: 'middle',
			type: 'fail',
		})
	}
}

// 修改预约
function editAppointment() {
	// 使用localStorage标记是修改预约操作，并强制立即写入
	localStorage.setItem('edit_appointment', 'true')
	console.log('标记为修改预约模式，准备跳转回首页')

	// 添加时间戳作为查询参数以确保路由始终发生变化
	const timestamp = Date.now()

	// 直接执行跳转，使用更明确的查询参数
	router.push({
		path: '/',
		query: {
			edit: 'true',
			t: timestamp.toString(),
			mode: 'edit_appointment', // 添加额外参数以确保URL变化
		},
	})
}

// 查看照片
function viewPhoto() {
	if (orderDetail.value.placementPhotoUrl) {
		// 使用函数调用方式打开图片预览
		showImagePreview({
			images: [orderDetail.value.placementPhotoUrl],
			closeable: true,
			closeOnPopstate: true,
		})
		console.log('打开图片预览:', orderDetail.value.placementPhotoUrl)
	} else {
		// 没有图片时显示提示
		showToast({
			message: t('delivery.noPhotoAvailable') || '暂无图片',
			position: 'middle',
		})
	}
}

// 返回上一页
function goBack() {
	router.back()
}
</script>

<style lang="scss" scoped>
.order-detail-page {
	width: 100%;
	min-height: 100vh;
	position: relative;
	background: #f3f4f6;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	padding-bottom: 40px;
}

// 顶部渐变背景
.top-gradient {
	width: 100%;
	height: 203px;
	position: absolute;
	left: 0;
	top: 0;
	background: linear-gradient(227deg, #e9f8d7 0%, #c6eefc 100%);
	z-index: 0;
}

// 模糊椭圆
.ellipse-1 {
	width: 249px;
	height: 206px;
	position: absolute;
	right: 0;
	top: 42px;
	background: rgba(255, 255, 255, 0.7);
	border-radius: 50%;
	filter: blur(50px);
	z-index: 1;
}

.ellipse-2 {
	width: 231px;
	height: 191px;
	position: absolute;
	left: -46px;
	top: 101px;
	background: rgba(255, 255, 255, 0.5);
	border-radius: 50%;
	filter: blur(50px);
	z-index: 1;
}

// 成功图标和文字
.success-section {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 70px;
	z-index: 2;
	position: relative;

	.success-icon {
		width: 48px;
		height: 48px;
		margin-right: 20px;
	}

	.success-text {
		font-size: 20px;
		font-weight: 700;
		color: #3c3c3c;
	}
}

// 导航栏样式
.custom-nav-bar {
	position: fixed;
	top: 0;
	width: 100%;
	z-index: 100;

	:deep(*) {
		background-color: transparent !important;
		border: none !important;
		box-shadow: none !important;
	}

	:deep(.van-nav-bar__title),
	:deep(.van-icon),
	:deep(.van-nav-bar__text) {
		color: #000 !important;
	}

	:deep(.van-hairline--bottom::after) {
		border: none !important;
		display: none !important;
	}
}

// 详情卡片
.detail-card {
	width: calc(100% - 26px);
	margin: 20px auto 0;
	background: white;
	border-radius: 15px;
	padding: 24px 20px;
	box-sizing: border-box;
	z-index: 2;
	position: relative;

	.info-section {
		display: flex;
		flex-direction: column;
		gap: 15px;

		.info-row {
			display: flex;
			align-items: center;

			.info-icon {
				width: 25px;
				height: 25px;
				margin-right: 10px;
				display: flex;
				align-items: center;
				justify-content: center;

				.icon {
					width: 20px;
					height: 20px;
					background-size: contain;
					background-repeat: no-repeat;
					background-position: center;
				}

				.profile-icon {
					background-image: url('@/assets/profile.svg');
				}

				.map-pin-icon {
					background-image: url('@/assets/location.svg');
				}

				.calendar-icon {
					background-image: url('@/assets/time.svg');
				}

				.phone-icon {
					background-image: url('@/assets/phone.svg');
				}
			}

			.info-content {
				flex: 1;
				color: #595959;
				font-size: 16px;
				font-weight: 600;
			}
		}
	}

	// 分割线
	.divider {
		height: 1px;
		background: #b1b1b2;
		margin: 20px 0;
		opacity: 0.5;
	}

	// 详细选项区
	.options-section {
		display: flex;
		flex-direction: column;
		gap: 10px;

		.option-row {
			display: flex;
			align-items: center;
			height: 32px;

			.option-label {
				min-width: 120px;
				color: #595959;
				font-size: 16px;
				font-weight: 600;
			}

			.option-value {
				color: #b1b1b1;
				font-size: 16px;
				font-weight: 600;
			}
		}
	}

	// 修改预约按钮
	.edit-btn {
		margin-top: 30px;
		text-align: center;
		color: #69d100;
		font-size: 16px;
		font-weight: 600;
		cursor: pointer;
	}
}

// 底部客服
.customer-service {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 5px;
	margin-top: auto;
	padding: 20px 0;

	span {
		color: #b7b7b7;
		font-size: 14px;
		font-weight: 600;
	}
}

// 底部安全区
.bottom-safe-area {
	height: 30px;
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

// 图标样式
.icon {
	color: #69d100;
}
</style>
